<template>
  <el-container>
    <el-aside class='fx-aside fx-bgc'>
      <el-row style='height: 60px;' class='fx-header-row fx-bgc'>
        <el-col :span='24' class='fx-header-col'>
          <div style='margin: 0 15px;'>
            <img title='返回主页' style='cursor: pointer;' @click='goHome' src='./assets/fengye.png' height='40'
                 alt='枫叶' />
          </div>
          <div class='fx-text-hidden'>
            <span class='fx-font'>枫桪物语管理系统</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span='24'>
          <el-menu
            unique-opened
            :default-active='activated'
            background-color='rgb(0, 22, 42)'
            text-color='rgb(166, 170, 174)'
            active-text-color='#fff'
            active-background-color='red'
            :collapse='isCollapse'
            :collapse-transition='false'
            @select='handleSelected'
          >
            <FxMenuItem v-if='menuData.length' :menus='menuData' />
          </el-menu>
        </el-col>
      </el-row>
    </el-aside>
    <el-container
      style='padding-top: 60px;height: 100vh;'>
      <el-header>
        <el-row style='height: 100%;' class='fx-header-row'>
          <el-col :span='1' class='fx-header-col-center'>
            <span
              class='fx-icon'
              @click='resetAside'
              :class='isCollapse ? "el-icon-s-unfold" :"el-icon-s-fold"' />
          </el-col>
          <el-col :span='6'>
            <span>欢迎进入枫桪物语后台管理系统</span>
          </el-col>
          <el-col :span='3' :offset='8' class='fx-header-col-center'>
            <el-autocomplete
              class='inline-input'
              v-model='menuSelect'
              :fetch-suggestions='querySearch'
              :placeholder='placeholder? placeholder : "搜索菜单"'
              @select='handleSelect'
              @focus='handleFocus'
            />
          </el-col>
          <el-col :span='1' class='fx-header-col-center'>
            <el-dropdown v-if='hasPermission' @command='handleCommand'>
              <el-avatar
                style='cursor: pointer;'
                :src='userData.avatar'
                title='枫桪'
                fit='contain'
                shape='square'
              />
              <el-dropdown-menu>
                <el-dropdown-item disabled>{{ userData.userName }}</el-dropdown-item>
                <el-dropdown-item command='exit'>退出登录</el-dropdown-item>
                <el-dropdown-item command='logOff'>注销登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
          <el-col :span='1'>
            <el-link :underline='false' type='info' icon='el-icon-s-home' href='/fxwy-home'>主页</el-link>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <router-view />
      </el-main>
      <el-footer style='display: flex;align-items: center;justify-content: center;'>
        <GlobalFooter />
      </el-footer>
    </el-container>
  </el-container>
</template>

<script>
import AuthorizeService from '@/service/users/AuthorizeService'
import pageUrl from '@/config/pageUrl'
import GlobalFooter from '@/components/GlobalFooter'
import FxMenuItem from '@/components/FxMenuItem'
import Filters from '@/tools/Filters'
import Sys_AdminService from '@/service/admin/Sys_AdminService'

export default {
  name: 'AdminPage',
  components: {
    GlobalFooter,
    FxMenuItem
  },
  data() {
    return {
      menuSelect: '',
      placeholder: '',
      restaurants: [],
      activated: '',
      isCollapse: false,
      menuData: [],
      asyncRoutes: [],
      hasPermission: false,
      userData: null
    }
  },
  created() {
    this.checkPermisson()
  },
  mounted() {
    const header = document.querySelector('.el-header')
    // 监听滚轮事件
    document.addEventListener('scroll', () => {
      if (window.scrollY > 0) {
        header.classList.add('top-fixed')
      } else {
        header.classList.remove('top-fixed')
      }
    })

  },
  methods: {
    // 主页鉴权 初始化数据
    async checkPermisson() {
      let res = await AuthorizeService.checkPermission()
      if (res.data.status !== 200) {
        // 无权限就跳转到无权限的提示页面 然后跳转回登录页面
        this.$message.error('无权访问，请先登录！')
        setTimeout(() => location.replace(pageUrl.login), 1500)
      } else {
        // 授权 允许访问本页面的基础功能
        this.hasPermission = true
        // 保存用户数据
        this.userData = res.data.data.userData
        sessionStorage.removeItem('userData')
        sessionStorage.setItem('userData', JSON.stringify(this.userData))
        this.initMenus()
      }
    },
    // 菜单初始化
    async initMenus() {
      if (sessionStorage.getItem('menus')) {
        this.menuData = JSON.parse(sessionStorage.getItem('menus'))
      } else {
        const res = await Sys_AdminService.getMenus()
        if (res.data.status !== 200) return this.$message.error(res.data.message)
        // 把菜单转为树结构
        let menus = Filters.getMenuTree(res.data.data.menus)
        // 对菜单进行排序并缓存
        Filters.sortMenu(menus)
        this.menuData = menus
        sessionStorage.removeItem('menus')
        sessionStorage.setItem('menus', JSON.stringify(this.menuData))
      }
      // 提取动态路由
      this.asyncRoutes = Filters.routesFormat(this.menuData)
      this.asyncRoutes.forEach(item => {
        this.$router.addRoute(item)
      })
      // 把菜单信息拉平缓存一下 方便给菜单管理组件使用
      const menuInfo = []
      this.asyncRoutes.forEach(item => {
        menuInfo.push({
          id: item.meta.id,
          title: item.meta.title
        })
      })
      sessionStorage.setItem('menuInfo', JSON.stringify(menuInfo))
      // 获取当前激活的菜单项
      const actived = sessionStorage.getItem('actived')
      const path = actived ? this.asyncRoutes.find(item => item.meta.id === actived).path : this.menuData[0].path
      // 默认选中第一个菜单 如果缓存里选中其他菜单，刷新的时候就跳转至对应的菜单
      this.activated = actived ? actived : this.menuData[0].id
      this.$router.push(path)
      this.restaurants = this.loadAll()
    },
    // 返回用户主页面
    goHome() {
      location.replace(pageUrl.user)
    },
    // 处理下拉选择
    handleCommand(command) {
      switch (command) {
        case 'exit':
          this.exit()
          break
        case 'logOff':
          this.logOff()
          break
        default:
          break
      }
    },
    // 退出
    exit() {
      sessionStorage.removeItem('authorization')
      sessionStorage.removeItem('userData')
      location.replace(pageUrl.login)
    },
    // 注销
    logOff(){
      sessionStorage.removeItem('authorization')
      sessionStorage.removeItem('userData')
      sessionStorage.removeItem('menus')
      sessionStorage.removeItem('menuInfo')
      sessionStorage.removeItem('actived')
      location.replace(pageUrl.user)
      this.$route.params.tab = 'articles'
    },
    querySearch(queryString, cb) {
      let restaurants = this.restaurants
      if (!this.menuSelect) {
        queryString = ''
      }
      let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll() {
      const menuList = []
      if (this.asyncRoutes.length) {
        let values = this.asyncRoutes.filter(item => !item.meta.hasChildren)
        values.forEach(item => menuList.push({
          value: item.meta.title,
          id: item.meta.id,
          path: item.path
        }))
      }
      return menuList
    },
    handleSelect(item) {
      if(this.activated === item.id) return
      this.activated = item.id
      // 缓存当前访问路径
      sessionStorage.setItem('actived', this.activated)
      this.$router.push(item.path)
    },
    handleFocus() {
      this.placeholder = this.menuSelect
      this.menuSelect = ''
    },
    handleSelected(index) {
      // 防止重复点击路由报错
      if(this.activated === index) return
      this.activated = index
      // 缓存当前访问路径
      sessionStorage.setItem('actived', index)
      const router = this.asyncRoutes.find(item => item.meta.id === index)
      this.$router.push(router.path)
    },
    resetAside() {
      this.isCollapse = !this.isCollapse
      const aside = document.querySelector('.el-aside')
      if (!this.isCollapse) {
        aside.classList.remove('fx-aside-scaled')
      } else {
        aside.classList.add('fx-aside-scaled')
      }
      // 通知数据总览组件重绘数据图表
      this.$events.$emit('resize')
    }
  },
  beforeDestroy() {
    this.$events.$off('resize')
  }
}
</script>

<style scoped>

.el-header {
  position: fixed;
  top: 0;
  z-index: 3;
  width: 100%;
  height: 60px !important;
  padding: 20px 0;
  margin: 0 auto;
  margin-bottom: 20px;
  border-bottom: 1px solid #ccc;
  background-color: #fff;
  transition: .3s;
}

.top-fixed {
  background-color: rgba(255, 255, 255, 0.8);
}

.el-select {
  width: 100px;
}

.el-input {
  margin-bottom: 0 !important;
}

.fx-aside {
  overflow: hidden;
  width: 260px !important;
  height: 100vh;
  transition: .5s;
}

.fx-aside-scaled {
  width: 70px !important;
  transition: .5s;
}

.fx-text-hidden {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.fx-header-row {
  display: flex;
  align-items: center;
}

.fx-header-col {
  display: flex;
  justify-content: start;
  align-items: center;
}

.fx-header-col-center {
  display: flex;
  justify-content: center;
}

.fx-bgc {
  background-color: rgb(0, 22, 42);
}

.fx-font {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

.fx-icon {
  cursor: pointer;
  font-size: 30px;
  color: gray;
}

.fx-icon:hover {
  color: #3a4965;
}

.el-avatar > img {
  width: 100%;
}

>>> .el-menu {
  width: 100%;
}

>>> .el-submenu .el-menu-item{
  background-color: rgb(0, 12, 23) !important;
}
>>> .el-submenu .el-menu-item:hover{
  background-color: rgb(0, 12, 23) !important;
}

>>> .el-menu-item:hover,
>>> .el-submenu__title:hover {
  background: none !important;
  color: #fff !important;
}


>>> .el-menu-item.is-active {
  background: rgb(250, 84, 28) !important;
  color: #fff !important;
}

>>> .el-menu-item.is-active:hover{
  background: rgb(250, 84, 28) !important;
}

>>> .el-main {
  background-color: rgb(240, 242, 245);
}

>>> .el-main::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}

>>> .el-footer {
  padding: 10px 20px !important;
  background-color: rgb(240, 242, 245);
}

>>> .el-footer p:hover >  a {
   color: rgb(250, 84, 28) !important;
}

</style>
